<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/02
 */

namespace app\admin\model\article;

use traits\ModelTrait;
use basic\BaseModel;
use app\admin\model\article\Article as ArticleModel;

/**
 * 文章分类model
 * Class ArticleCategory
 * @package app\admin\model\wechat
 */
class ArticleCategory extends BaseModel
{
    use ModelTrait;

    protected $pk = 'id';

    protected $name = 'article_category';

    protected $autoWriteTimestamp = true;


        /**
     * 获取列表
     * @param array $where 查询条件
     * @return void
     * @author Sam
     * @date 2020-09-28
     */
    public static function getList($where = []){
        $data  = self::setWhere($where)->page((int)$where['page'],(int)$where['limit'])->order('id desc')->select();
        $data  = count($data) ? $data->toArray() : [];
        $count = self::setWhere($where)->count();
        return compact('data','count');
    }


        /**
     * 获取查询条件
     * @param $where
     * @param string $alert
     * @param null $model
     * @return SystemUserLevel|null
     */
    public static function setWhere($where,$alert='',$model=null)
    {
        $model = $model===null ? new self() : $model;
        if ($where['title'] != '') $model = $model->where('title', 'LIKE', "%$where[title]%");
        return $model;
    }



    /**
     * 删除分类
     * @param $id
     * @return bool
     */
    public static function delArticleCategory($id)
    {
        if(ArticleModel::where('cid','in',$id)->count()){
            return self::setErrorInfo('请先删除分类下的文章!');
        }
        return self::destroy($id);
    }

    /**
     * 获取分类名称和id
     * @return array
     */
    public static function getField()
    {
        return self::where('is_del', 0)->where('status', 1)->where('hidden', 0)->column('title', 'id');
    }

    /**
     * 分级排序列表
     * @param null $model
     * @return array
     */
    public static function getTierList($model = null)
    {
        if ($model === null) $model = new self();
        return sort_list_tier($model->where('is_del', 0)->where('status', 1)->select()->toArray());
    }



    /**
     * TODO 获取文章分类
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getArticleCategoryList()
    {
        $list = self::where('is_del', 0)->where('status', 1)->select();
        if ($list) return $list->toArray();
        return [];
    }

    /**
     * TODO 获取文章分类信息
     * @param $id
     * @param string $field
     * @return mixed
     */
    public static function getArticleCategoryInfo($id, $field = 'title')
    {
        $model = new self;
        if ($id) $model = $model->where('id', $id);
        $model = $model->where('is_del', 0);
        $model = $model->where('status', 1);
        return $model->column($field, 'id');
    }

}